package cn.edu.zju.om.analyse;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class FeatureVectorFactory {

	
	public FeatureVectorFactory() {
	}
	
	public List<PhraseFeatureVector> buildFeatureVectors(Map<String, Phrase> phraseMap) {
		List<PhraseFeatureVector> ret = new ArrayList<PhraseFeatureVector>();
		
		
		Map<String, Integer> modifierTable = buildModifierTable(phraseMap);
		
		for(Entry<String, Phrase> entry : phraseMap.entrySet()) {
			Phrase phrase = entry.getValue();
			double[] featureArray = buildEmptyArray(modifierTable.size());
			if (phrase.getCount() > 1) {
				Map<String, Modifier> modifiers = phrase.getModifiers();
				
				for(Entry<String, Modifier> modifierEntry : modifiers.entrySet()) {
					String modifierName = modifierEntry.getKey();
					Modifier modifier = modifierEntry.getValue();
					
					int index = modifierTable.get(modifierName).intValue();
					featureArray[index] = modifier.getCount();
//					if (modifier.getCount() > 1) {
//						featureArray[index] = 1;
//					}
					
				}
			}
			
			//normalizeArray(featureArray);
			
			PhraseFeatureVector featureVector = new PhraseFeatureVector(phrase, featureArray);
			
			ret.add(featureVector);
		}
		
		return ret;
	}

	private void normalizeArray(double[] featureArray) {
		double mod = 0;
		for(double num : featureArray) {
			mod += num;
		}
		
		for(int i = 0; i < featureArray.length; ++i) {
			featureArray[i] /= mod;
		}
	}

	private Map<String, Integer> buildModifierTable(
			Map<String, Phrase> phraseMap) {
		Map<String, Integer> modifierTable = new HashMap<String, Integer>();
		int indexNumber = 0;
		
		for(Entry<String, Phrase> entry : phraseMap.entrySet()) {
			Phrase phrase = entry.getValue();
			if (phrase.getCount() > 1) {
				Map<String, Modifier> modifiers = phrase.getModifiers();
				
				for(String modifierName : modifiers.keySet()) {
					if(!modifierTable.containsKey(modifierName)) {
						modifierTable.put(modifierName, new Integer(indexNumber++));
					}
				}
			}
		}
		return modifierTable;
	}
	
	public double[] buildEmptyArray(int length) {
		double[] emptyArray = new double[length];
		for(int i = 0; i < emptyArray.length; ++i) {
			emptyArray[i] = 0;
		}
		
		return emptyArray;
	}

}
